<template>
  <Sphere :args="[16, 32, 32]" :position="[0, 0, 0]" :scale="[1, 1, -1]">
    <!-- <TresMeshStandardMaterial ref="material" :map="envMap" :side="THREE.DoubleSide" /> -->
    <TresShaderMaterial :vertex-shader="vertexShader" :fragment-shader="fragmentShader" :uniforms="uniforms" :side="THREE.DoubleSide"  />
    <CtHtml 
      v-for="item in room?.hotPoints" :key="item.key"
      center transform sprite :distance-factor="8"
      :position="item.pos"
    >
      <HotRoomInfo :info="item" />
    </CtHtml>
  </Sphere>
</template>

<script setup lang="ts">
import * as THREE from 'three'
import { shallowRef, ref, onMounted } from 'vue'
import { useTexture,useRenderLoop } from '@tresjs/core'
import { Sphere, Html as CtHtml } from '@tresjs/cientos'
import { emitter } from '@/utils/mitt'
import { storeToRefs } from 'pinia'
import { useRoomStore } from '@/stores/useRoomStore'
import HotRoomInfo from './HotRoomInfo.vue'
import vertexShader from '@/glsl/tran.glsl'
import fragmentShader from '@/glsl/tran.frag'

const emit=defineEmits(['updateCtrl'])
const { onBeforeLoop } = useRenderLoop()
const store = useRoomStore()
const { rooms, room, key } = storeToRefs(store)

const matMap: any = {}
const material = ref()
const envMap = shallowRef()

const uniforms=ref({
  map1:{
    value:null
  },
  map2:{
    value:null
  },
  progress:{
    value:0
  }
})

emitter.on('room:switch', async item => {
  if (item.key === key.value) return
  loadEnvMap(item)
})
onMounted(async () => {
  await loadRoomsMap()
  loadEnvMap(room.value)
})
async function loadRoomsMap() {
  const textures=await Promise.all(rooms.value.map(v =>useTexture([v!.map])))
  textures.forEach((v,i) =>{
    const _room = rooms.value[i]
    matMap[_room!.key] = v
  })
}
async function loadEnvMap(item: any) {
  //envMap.value = matMap[item.key]
  //material.value.needsUpdate = true
  uniforms.value.map1.value=matMap[key.value]
  key.value = item!.key
  uniforms.value.map2.value=matMap[item.key]
  uniforms.value.progress.value=0
  onBeforeLoop(() =>{
    if(uniforms.value.progress.value<1) uniforms.value.progress.value+=0.005
  })
  emit('updateCtrl')
}
</script>

<style scoped></style>